<template>
  <div>
    <customDialog
      :title="`选择${
        userTemData ? '(' + userTemData?.userName + ')' : ''
      }用户小程序`"
      :dialogVisible="dialogVisible"
      @close="dialogVisible = false"
      @confirm="confirmDialog"
      :showFoot="userTemData ? false : true"
      :showCancel="userTemData ? false : true"
      :show-close="false"
      :closeESC="false"
      width="600"
    >
      <div class="table_box_wrapper">
        <custom-table
          :loading="loading"
          :columns="columns"
          :tableData="tableData"
          :isPagination="false"
          :maxHeight="500"
          class="table_box"
        >
          <template #operator="{ scope }">
            <el-button type="primary" @click.stop="handleAllocation(scope.row)">
              {{ btnText }}
            </el-button>
          </template>
        </custom-table>
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import customDialog from "@/components/CustomDialog/index.vue";
import customTable from "@/components/CustomTable/index.vue";
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import { getAppsList } from "@/api/auth/index";
import { useUserStore } from "@/store/modules/user";
import { allocationUserApp } from "@/api/globalManage/appletRoute/index";
import { debounce } from "lodash-es";

const props = defineProps({
  btnText: {
    type: String,
    default: "点击进入",
  },
});
const userTemData = ref();

const dialogVisible = ref(false);
const userStore = useUserStore();
const loading = ref<boolean>(false);
const tableData = ref<Array<any>>([]);

const columns = reactive([
  { prop: "appId", label: "小程序ID", minWidth: 150 },
  { prop: "appName", label: "小程序名称", minWidth: 120 },
  {
    prop: "appType",
    label: "小程序类型",
    minWidth: 120,
    formatter(val: any) {
      return val.appType === "wx" ? "微信" : val.appType === "dy" ? "抖音" : "";
    },
  },
  { prop: "operator", slotName: "operator", label: "操作", width: 120 },
]);

// 绑 定 / 分配
const handleAllocation = debounce((val: Record<string, any>) => {
  console.log("userTemData-----", userTemData.value);

  if (userTemData.value) {
    let params = {
      userId: userTemData.value.id.toString(),
      appIds: [val?.id],
    };
    allocationUserApp(params).then(() => {
      // ElMessage.success("分配小程序成功");
      ElMessage.success(
        `用户（${userTemData.value.userName}）分配小程序成功，请前往登录`
      );
      dialogVisible.value = false;
    });
  } else {
    const userName = userStore.user.userName;
    userStore.switchAppid(val?.id);
    userStore.setAppObj(val); // 存储登录绑定小程序对象到store上
    dialogVisible.value = false;
    localStorage.setItem(`@${userName}`, val?.id);
    location.reload();
  }
}, 100);

// 确定
const confirmDialog = () => {
  ElMessage.success(`用户（${userTemData.value.userName}）已新增，请前往登录`);
  dialogVisible.value = false;
};

const getList = () => {
  loading.value = true;
  getAppsList()
    .then((res: any) => {
      tableData.value = res;
      dialogVisible.value = true;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 父级电子显示dialog
const showDialog = (val = null) => {
  console.log("显示弹窗 *-----", val);
  // 如果有值，则为新增用户下一步操作，如果没值则为切换当前小程序操作
  if (val) {
    userTemData.value = val;
  } else {
    userTemData.value = null;
  }
  getList();
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss">
.form_box {
  padding: 0 20px;
}
</style>
